<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.storeName"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="输入渠道名称"
      />
      <el-select v-model="listQuery.status" clearable style="width: 200px" class="filter-item" placeholder="请选择状态" >
        <el-option v-for="(item,index) in statusMap" :key="index" :label="item.name" :value="item.value" />
      </el-select>
      <el-button
        v-permission="['store:store:list']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button>
      <el-button
        v-permission="['store:store:create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      style="white-space: pre-line"
    >
      <el-table-column prop="storeName" align="center" label="渠道名称"/>
      <el-table-column prop="storeType" align="center" label="渠道类型">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.storeType === 0? '加盟': '直营' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isOnlineSale" align="center" label="线上销售">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.isOnlineSale === 0? '否': '是' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="contactName" align="center" label="联系人"/>
      <el-table-column prop="contactPhone" align="center" label="联系电话"/>
      <el-table-column prop="status" align="center" label="状态">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.status === 0? '禁用': '正常' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="storeUsername" align="center" label="账号"/>
      <el-table-column align="center" label="创建时间" prop="gmtCreate">
        <template slot-scope="scope">{{ scope.row.gmtCreate | formatGmt }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-permission="['store:store:update']"
            v-if="scope.row.status=='1'"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            v-permission="['store:store:active']"
            v-if="scope.row.status=='1'"
            type="danger"
            size="mini"
            @click="handleStatus(scope.row)"
          >冻结</el-button>
          <el-button
            v-permission="['store:store:active']"
            v-else
            type="primary"
            size="mini"
            @click="handleStatus(scope.row)"
          >激活</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :width="optDiaLogWidth" :title="textMap[dialogStatus]" :custom-class="dialogClass" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="渠道编号" prop="storeNo">
          <el-input v-model="dataForm.storeNo" clearable placeholder=""/>
        </el-form-item>
        <el-form-item label="渠道名称" prop="storeName" >
          <el-input
            v-model="dataForm.storeName"
            clearable
            maxlength="15"
            show-word-limit
            placeholder="不能超过15个字"/>
        </el-form-item>
        <el-form-item label="渠道地址" prop="storeAddress">
          <el-row>
            <el-col :span="20">
              <el-input
                v-model="dataForm.storeAddress"
                clearable
                placeholder="不能超过50个字"
                maxlength="50"
                type="textarea"
                rows="3"
                show-word-limit/>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="渠道logo" prop="storeLogo">
          <el-upload
            :action="uploadPath"
            :before-upload="onBeforeUpload"
            :show-file-list="false"
            :on-success="handleLogoImgSuccess"
            accept="image/jpeg,image/jpg,image/png,image/bmp"
            class="avatar-uploader">
            <img v-if="dataForm.storeLogo" :src="dataForm.storeLogo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="负责人" prop="contactName">
          <el-input v-model="dataForm.contactName" clearable placeholder=""/>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactPhone">
          <el-input v-model="dataForm.contactPhone" clearable placeholder=""/>
        </el-form-item>
        <el-form-item label="账号" prop="storeUsername">
          <el-input v-model="dataForm.storeUsername" clearable placeholder="不同渠道的账号不能重复,使用手机号"/>
        </el-form-item>
        <el-form-item label="密码" prop="storePassword">
          <el-input v-model="dataForm.storePassword" show-password clearable placeholder="" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.el-table .cell {
  white-space: pre-line;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.el-form :not(.is-required) > .el-form-item__label{
  padding-left: 10px;
}
.dialogClass .el-dialog__body{
  padding-bottom: 0;
  padding-top: 10px;
}
.dialogClass .el-dialog__footer{
  padding-top: 0;
}
.map {
  width: 120%;
  height: 300px;
}
</style>

<script>
import { active, create, del, list, update } from '@/api/store'
import { uploadPath } from '@/api/storage'
import { formatDateAndTime } from '@/filters'
import BaiduMap from 'vue-baidu-map/components/map/Map'
import BmMarker from 'vue-baidu-map/components/overlays/Marker'
import BmView from 'vue-baidu-map/components/map/MapView'
import BmLocalSearch from 'vue-baidu-map/components/search/LocalSearch'
import BmInfoWindow from 'vue-baidu-map/components/overlays/InfoWindow'
import BmLabel from 'vue-baidu-map/components/overlays/Label'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
export default {
  name: 'Store',
  components: {
    Pagination,
    BaiduMap,
    BmView,
    BmMarker,
    BmLabel,
    BmLocalSearch,
    BmInfoWindow },
  filters: {
    formatGmt(time) {
      if (time == null || time === '') {
        return '无'
      }
      return formatDateAndTime(time)
    }
  },
  data() {
    return {
      uploadPath,
      statusMap: [{ value: 0, name: '禁用' }, { value: 1, name: '正常' }],
      list: undefined,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        limit: 20,
        status: undefined,
        gmtStartCreate: undefined,
        gmtEndCreate: undefined
      },
      options: [],
      dataForm: {
        id: undefined,
        storeType: 1,
        storeLogo: undefined,
        storeDeliveType: 1,
        isOnlineSale: 1,
        contactName: '大牛来了',
        storeStartTime: new Date('08:00'),
        storeEndTime: new Date('18:00'),
        storeLalg: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      gmtDay: undefined,
      rules: {
        storeType: [
          { required: true, message: '请选择经营模式', trigger: 'blur' }
        ],
        storeName: [
          { required: true, message: '请输入渠道名称', trigger: 'blur' }
        ],
        storeDeliveType: [
          { required: true, message: '请选择配送方式', trigger: 'blur' }
        ],
        contactName: [
          { required: true, message: '请输入负责人', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入负责人手机', trigger: 'blur' }, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确电话' }
        ],
        storeStartTime: [
          { required: true, message: '请选择开始时间', trigger: 'blur' }
        ],
        storeEndTime: [
          { required: true, message: '请选择结束时间', trigger: 'blur' }
        ],
        storeUsername: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        storePassword: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      optDiaLogWidth: '54%',
      dialogClass: 'dialogClass',
      keyword: '',
      location: '北京',
      center: { lng: 0, lat: 0 },
      isShowPanel: true,
      zoom: 3,
      markerPos: { lng: 0, lat: 0 }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      list(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        storeType: 1,
        storeLogo: undefined,
        storeDeliveType: 1,
        isOnlineSale: 1,
        contactName: '',
        storeStartTime: new Date('08:00'),
        storeEndTime: new Date('18:00'),
        storeLalg: '',
        storeLg: undefined,
        storeLa: undefined
      }
      this.keyword = undefined
      this.center = { lng: 116.404, lat: 39.915 }
      this.zoom = 15
      this.markerPos = { lng: 116.404, lat: 39.915 }
    },
    handleStatus(row) {
      this.resetForm()
      this.dataForm.id = row.id
      this.dataForm.status = row.status === 1 ? 0 : 1
      active(this.dataForm)
        .then(res => {
          this.$notify.success({
            title: '成功',
            message: '状态更改成功'
          })
          this.getList()
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.initHandler()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          create(this.dataForm)
            .then(response => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: '失败'
              })
            })
        }
      })
    },
    handleUpdate(row) {
      if (row && row.storeTime) {
        var timeRange = row.storeTime.split('-')
        var storeStartTime = timeRange[0]
        var storeEndTime = timeRange[1]
        if (storeEndTime && storeStartTime) {
          row.storeStartTime = storeStartTime
          row.storeEndTime = storeEndTime
        }
      }
      this.dataForm = Object.assign({}, row)
      if (row.storeLalg && row.storeLalg.indexOf(',') > -1) {
        const laLg = row.storeLalg.split(',')
        this.$set(this.dataForm, 'storeLg', laLg[0])
        this.$set(this.dataForm, 'storeLa', laLg[1])
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.initHandler()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataForm.storeLg && this.dataForm.storeLa) {
            this.dataForm.storeLalg = this.dataForm.storeLg + ',' + this.dataForm.storeLa
          }
          update(this.dataForm)
            .then(response => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: '失败'
              })
            })
        }
      })
    },
    onBeforeUpload(file) {
      var isIMAGE = (file.type === 'image/jpeg' || 'image/jpg' || 'image/png' || 'image/bmp')
      var isLt2M = (file.size / 1024 / 1024 < 2)
      if (!isIMAGE) {
        this.$notify.error({
          title: '失败',
          message: '失败'
        })
      }
      if (!isLt2M) {
        this.$notify.error({
          title: '失败',
          message: '失败'
        })
      }
      return isIMAGE && isLt2M
    },
    handleLogoImgSuccess(e, file) {
      this.dataForm.storeLogo = e.url
      this.dialogFormVisible = false
      this.dialogFormVisible = true
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: '失败'
            })
          })
      }).catch(() => {
        return false
      })
    },
    searchOnMap() {
      this.$set(this, 'keyword', this.dataForm.storeAddress)
    },
    initHandler() {
      if (this.dataForm.storeLalg && this.dataForm.storeLalg.indexOf(',') > -1 && this.dialogStatus === 'update') {
        const laLg = this.dataForm.storeLalg.split(',')
        this.center.lng = laLg[0]
        this.center.lat = laLg[1]
        this.zoom = 15
        this.markerPos.lng = laLg[0]
        this.markerPos.lat = laLg[1]
      } else {
        this.center.lng = 117.941563
        this.center.lat = 33.912598
        this.zoom = 15
        this.markerPos.lng = 117.941563
        this.markerPos.lat = 33.912598
      }
    },
    syncCenterAndZoom(e) {
      const location = e.target.getCenter()
      this.$set(this.dataForm, 'storeLa', location.lat)
      this.$set(this.dataForm, 'storeLg', location.lng)
    },
    getClickInfo(e) {
      this.$set(this.dataForm, 'storeLa', e.point.lat)
      this.$set(this.dataForm, 'storeLg', e.point.lng)
    }
  }
}
</script>
